/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.ecommerce.erro;

import java.util.HashSet;
import java.util.Iterator;
import java.util.ResourceBundle;
import java.util.Set;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author rpateixeira
 */
public class EcomerceExceptionHandler extends ExceptionHandlerWrapper {

     private ExceptionHandler handler;
    protected ResourceBundle myResources = ResourceBundle.getBundle("messages");
    public EcomerceExceptionHandler(ExceptionHandler exceptionHandler) {
        this.handler=exceptionHandler;
    }
    @Override
    public void handle() throws FacesException {
        FacesContext fc = FacesContext.getCurrentInstance();

        for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
            ExceptionQueuedEvent event = i.next();
            ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
            Throwable t = context.getException();

            Set<String> messages = trataExcecao(t);

            if (messages!=null&&!messages.isEmpty()){
                boolean isAjaxRequest = fc.getPartialViewContext().isAjaxRequest()||fc.getPartialViewContext().isPartialRequest();
                if (!isAjaxRequest){
                    String pfAjaxRequest = ((HttpServletRequest) fc.getExternalContext().getRequest()).getParameter("primefacesPartialRequest");
                    isAjaxRequest = pfAjaxRequest!=null&&Boolean.parseBoolean(pfAjaxRequest);
                }

                if (isAjaxRequest){
                	for (String mes : messages){
                		addExceptionMessage(mes);
                	}
                    if (!fc.getPartialViewContext().getRenderIds().contains("mensagens")){
                        fc.getPartialViewContext().getRenderIds().add("mensagens");
                    }
                }else{
                	for (String mes : messages){
                		addErrorMessage(mes);
                	}
                }
            }
            fc.getApplication().getNavigationHandler().
            handleNavigation(fc, fc.getViewRoot().getViewId(), null);
        }

        getWrapped().handle();
    }

    private Set<String> trataExcecao(Throwable t){
        while  (t.getCause()!=null){
            t = t.getCause();
        }
        try{
            throw t;
        }catch(ExceptionList e){
        	e.printStackTrace();
        	HashSet<String> messages = new HashSet<String>();
        	for (Exception ex : e.getListaErros()){
        		messages.add(myResources.getString("ecomerce.error."+ex.getMessage()));
        	}
        	return messages;
        }catch (PersistenceException e){
        	e.printStackTrace();
        	HashSet<String> set = new HashSet<String>();
        //	set.add(myResources.getString("ecomerce.error."+e.getMessage()));
        	return set;
        }catch(Throwable tt){
            tt.printStackTrace();
        	HashSet<String> set = new HashSet<String>();
        	set.add(myResources.getString("ecomerce.error.erroRequisicao"));
        	return set;
        }
    }

    protected void addExceptionMessage(String error){
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, error, null));
    }

    protected void addErrorMessage(String error){
        FacesContext.getCurrentInstance().addMessage("errorMessage", new FacesMessage(FacesMessage.SEVERITY_ERROR, error, null));
    }
    @Override
    public ExceptionHandler getWrapped() {
        return handler;
    }
}
